#include <Windows.h>
#include <string.h>

#include "common.h"
#include "Log.h"


// Constructor
Log::Log() {
	path = NULL;
	output = NULL;
}
Log::Log(char *_path) {
	path = new char[strlen(_path) + 1];
	strcpy(path, _path);

	open(path);
}

// Deconstructor
Log::~Log() {
	// close the file
	if(output) {
		fclose(output);
	}

	// delete the log, this way log only exists in the case of a crash
#ifdef _DEBUG
	printf("[log] deleting: '%s'\n", path);
#endif // _DEBUG
	remove(path);

	if(path) {
		delete[] path;
	}
}

// switch to specified path for output
bool Log::open(char *_path) {
	path = new char[strlen(_path) + 1];
	strcpy(path, _path);

	output = fopen(path, "w");
	return (output != NULL);
}

// write to file
int Log::write(char *data) {
	if(output)
		return write(data, strlen(data));
	return 0;
}

// write to file, specify bytes
int Log::write(char *data, int num_bytes) {
	char buffer[DEFAULT_BUFLEN];

	if(output) {
		// generate/output timestamp
		ULONGLONG timestamp = GetTickCount64();
		sprintf(buffer, "[%llu] ", timestamp);
		int count = fwrite(buffer, 1, strlen(buffer), output);

		// output the data
		count += fwrite(data, 1, num_bytes, output);

		// flush the log data
		fflush(output);

		return count;
	}
	return 0;
}